package db

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"leaf/core/conf"
)

var mgo *mongo.Client

func InitMongo(addr string) {
	if addr == "" {
		panic("addr is nil")
	}

	var err error
	mgo = new(mongo.Client)

	var url = options.Client().ApplyURI(fmt.Sprintf("mongodb://%v", addr))
	if mgo, err = mongo.Connect(context.TODO(), url); err != nil {
		panic(err)
	}
	if err = mgo.Ping(context.Background(), readpref.Primary()); err != nil {
		panic(err)
	}

}

func GetMongo() *mongo.Client {
	if mgo == nil {
		var err error
		var url = options.Client().ApplyURI(fmt.Sprintf("mongodb://%v", conf.Config.MongoAddr))
		mgo, err = mongo.Connect(context.TODO(), url)
		if err != nil {
			return nil
		}
		err = mgo.Ping(context.Background(), readpref.Primary())
		if err != nil {
			return nil
		}
	}
	return mgo
}
